# -*- coding:utf-8 -*-
import csv
import io
from IPy import IP
from netaddr import IPAddress
import socket

def cidr2StartEnd_idc(listStr, sheetStr):
    if isinstance(listStr, list):
        if listStr.__le__(1):
            print('the listStr length is 0,continue...')
        else:
            exit(2)
    else:
        return ''
    iplist = []
    # cidr
    ip = IP(listStr[0], make_net=True)
    # 开始ip转换为整数
    ip_start_int = ip.net().int()
    # 结束ip转换为整数
    ip_end_int = ip.broadcast().int()
    ip_mask_int = IPAddress(str(ip.netmask())).netmask_bits()

    singleList = [ip_start_int, ip_end_int, ip_mask_int, listStr[2], listStr[1]]
    iplist.append(singleList)
    return iplist


def is_ipv4(ip):
    try:
        socket.inet_aton(ip)  # 尝试将IP转换为网络字节序的32位整数
        return True
    except socket.error:
        return False


# 适用于将 ch 字典转换为  doris udf 适用的资源文件
if __name__ == '__main__':
    # 用户群资源
    ipv4 = io.open("/tmp/sc_zqy_usergroup/tr_global_ip.csv", "wb")
    ipv6 = io.open("/tmp/sc_zqy_usergroup/tr_global_ipv6.csv", "wb")
    writer_v4 = csv.writer(ipv4)
    writer_v6 = csv.writer(ipv6)

    with open('/tmp/sc_zqy_usergroup/tr_usergroup_addr_cidr.csv', 'r') as f:
        reader = csv.reader(f)
        for row in reader:
            reipList = cidr2StartEnd_idc(row, '')
            if is_ipv4(row[0].split('/')[0]):
                writer_v4.writerows(reipList)
            else:
                writer_v6.writerows(reipList)

    ipv4.close()
    ipv6.close()
